﻿using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace TL_Cloud.API.Helpers
{
    /// <summary>
    /// HangFire定时服务
    /// </summary>
    public class HangfireTimeService : BackgroundService
    {
        public ILogger _logger;
        public HangfireTimeService(ILogger<HangfireTimeService> logger)
        {
            this._logger = logger;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                _logger.LogInformation(DateTime.Now.ToString() + "HangfireTimeService：启动");

                //while (!stoppingToken.IsCancellationRequested)
                //{
                //    await Task.Delay(5000, stoppingToken); //启动后5秒执行一次 (用于测试)
                //    _logger.LogInformation(DateTime.Now.ToString() + " 执行逻辑");
                //}

                _logger.LogInformation(DateTime.Now.ToString() + "HangfireTimeService：停止");
            }
            catch (Exception ex)
            {
                if (!stoppingToken.IsCancellationRequested)
                {
                    _logger.LogInformation(DateTime.Now.ToString() + "HangfireTimeService：异常" + ex.Message + ex.StackTrace);
                }
                else
                {
                    _logger.LogInformation(DateTime.Now.ToString() + "HangfireTimeService：停止");
                }
            }
        }       
    }
}
